$m(function (args) {
    var $mainDialog = $('#tempo-mine-snapshot-layout');
    var $confirmDialog = $('#tempo-mine-snapshot-confirm-layout');
    var $datagrid = $('#tempo-mine-snapshot-datagrid');

    //主题ID
    var analyseId = args.analyseId;
    //场景ID
    var $resourceId = args.resourceId;
    //场景内容
    var $content = args.content;

    /**
     * 初始化入口
     */
    var init = function () {
        renderDialog();
    }

    var renderDialog = function () {
        $mainDialog.dialog({
            title: TempoUtils.locale("mine.snapshot_manage"),
            autoOpen: true,
            width: 1000,
            height: 600,
            resizable: false,
            modal: true,
            close: function () {
                $mainDialog.dialog('destroy').remove();
            },
            open: function () {
                dataGridBuilder.render();
            },
            buttons: [{
                text: TempoUtils.locale("core.close"),
                click: function () {
                    $mainDialog.dialog('close');
                }
            }]
        });
    }

    /**
     * 构建列表
     */
    var dataGridBuilder = {
        render: function () {
            dataGridBuilder._buildGrid();
        },

        _buildGrid: function () {
            var colNames = dataGridBuilder._getColNames();
            var colModel = dataGridBuilder._getColModel();
            $datagrid.datagrid({
                colNames: colNames,
                colModel: colModel,
                url: contextPath + '/api/ai/snapshot/query',
                postData: {
                    id: $resourceId,
                    analyseId: analyseId
                },
                multiselect: true,
                rownumbers: true,
                fit: true,
                datatype: 'json',
                loadui: 'disable',
                autowidth: true,
                pagination: true,
                shrinkToFit: true,
                toolbar: dataGridBuilder._getToolbar(),
                onSelectRow: function (rowId, status, event) {
                    var selectAllBtn = $mainDialog.find(".ui-jqgrid-hdiv").find("table").find("th:nth-child(2)").find("input[role=checkbox]");
                    //兼容手动全选
                    if ($datagrid.datagrid("getSelectRowIds").length === $datagrid.datagrid("getRowData").length) {
                        selectAllBtn.checkbox('option', 'checked', true);
                    } else {
                        selectAllBtn.checkbox('option', 'checked', false);
                    }
                },
            });
        },

        /**
         * 列表名称
         */
        _getColNames: function () {
            return [TempoUtils.locale("mine.snapshot_version"),
                TempoUtils.locale("mine.snapshot_name"),
                TempoUtils.locale("mine.snapshot_author"),
                TempoUtils.locale("mine.snapshot_create_time"),
                TempoUtils.locale("mine.snapshot_remark"), 'ID',
                TempoUtils.locale("mine.snapshot_theme_id"),
                TempoUtils.locale("mine.snapshot_scene_id"),
                TempoUtils.locale("mine.base_operator")];
        },

        /**
         * 列表列模型
         */
        _getColModel: function () {
            return [{
                name: 'versionNumber',
                sortable: false,
                width: 70,
                formatter: function (arg1, arg2) {
                    return "V" + arg1;
                }
            }, {
                name: 'name',
                sortable: false
            }, {
                name: 'creatorName',
                width: 80,
                sortable: false
            }, {
                name: 'createTime',
                sortable: false,
                width: 110,
                formatter: function (arg1, arg2) {
                    return DateUtils.formatDateTime(arg1);
                }
            }, {
                name: 'remark',
                sortable: false
            }, {
                name: 'id',
                hidden: true
            }, {
                name: 'appId',
                hidden: true
            }, {
                name: 'resourceId',
                hidden: true
            }, {
                name: 'manage',
                resizeable: false,
                sortable: false,
                align: 'left',
                width: 80,
                fixed: false,
                buttons: dataGridBuilder._getButtons()
            }];
        },
        _getButtons: function () {
            return [{
                title: TempoUtils.locale("mine.snapshot_preview"),
                id: "preview",
                icon: "ui-icon tempo-ui-icon tempo-ui-icon-preview",
                click: function (e, dt) {
                    e.stopPropagation()
                    eventSet.toPreviewClick(dt.rowData);
                    return false;
                }
            }, {
                title: TempoUtils.locale("mine.snapshot_rollback"),
                id: "rollback",
                icon: "ui-icon tempo-ui-icon tempo-ui-icon-snapshot-rollback",
                click: function (e, dt) {
                    e.stopPropagation()
                    eventSet.toRollbackClick(dt.rowData);
                    return false;
                }
            }]
        },

        /**
         * 列表工具条
         */
        _getToolbar: function () {
            return [{
                id: '_snapshot_remove',
                text: TempoUtils.locale("mine.snapshot_remove"),
                click: function (e) {
                    eventSet.remove();
                }
            }];
        }
    }

    /**
     * 事件集合
     */
    var eventSet = {

        /**
         * 删除
         */
        remove: function () {
            var rowIds = $datagrid.datagrid('getSelectRowIds');
            if (!rowIds || rowIds.length <= 0) {
                $("<div/>").alert({
                    msg: TempoUtils.locale("mine.snapshot_select_one_remove")
                });
                return;
            }
            $("<div/>").confirm({
                msg: TempoUtils.locale("mine.data_base_confirm_delete"),
                ok: function () {
                    var process = $("<div/>").tempoprogressbar();
                    $.ajax({
                        url: contextPath + '/api/ai/snapshot/delete',
                        data: {
                            ids: JSON.stringify(rowIds)
                        },
                        type: 'post',
                        success: function (resultData) {
                            process.tempoprogressbar('destroy');
                            if (resultData.success) {
                                $datagrid.datagrid('reloadGrid');
                                $("<div/>").alert({
                                    msg: TempoUtils.locale("mine.snapshot_remove_success")
                                });
                            } else {
                                $("<div/>").alert({
                                    msg: TempoUtils.locale("mine.snapshot_remove_fail")
                                });
                            }
                        },
                        error: function () {
                            process.tempoprogressbar('destroy');
                        }
                    });
                }
            });
        },

        /**
         * 预览
         */
        toPreviewClick: function (rowData) {
            eventSet.executePreview(rowData);
        },

        /**
         * 执行预览
         */
        executePreview: function (resource) {
            var url = contextPath + '/api/ai/snapshot/view/overview?id=' + resource.id;
            window.open(url, "_blank");
        },

        /**
         * 回滚事件
         */
        toRollbackClick: function (rowData) {
            eventSet.confirmToSnapshot(rowData);
        },

        /**
         * 确认是否将当前场景保存快照
         */
        confirmToSnapshot: function (rowData) {
            $confirmDialog.dialog({
                autoOpen: true,
                width: 400,
                height: 250,
                resizable: false,
                modal: true,
                close: function () {
                    $confirmDialog.dialog('destroy').remove();
                },
                open: function () {
                    eventSet.bindComfirmButtonClick(rowData);
                }
            })
        },

        /**
         * 按钮绑定事件
         */
        bindComfirmButtonClick: function (rowData) {
            var buttons = $confirmDialog.find('.tempo-mine-snapshot-confirm-button');
            buttons.unbind('click').bind('click', function () {
                var buttontype = $(this).attr("value");
                //先快照后恢复
                if (buttontype == '1') {
                    $mainDialog.dialog('close');
                    $confirmDialog.dialog('close');
                    var url = contextPath + '/api/ai/snapshot/view/add';
                    var analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0];
                    var id = analyseStatus.getMainId();
                    var page = analyseStatus.getFlowPanel(id);
                    var data = page.panel.flowpanel('getRootData');
                    // 去除重复的flowReadyData(与flow重复)
                    delete data.flowReadyData
                    var analyseId = window[constant.ANALYSE_ID];
                    var param = {
                        analyseId: analyseId,
                        resourceId: id,
                        content: JSON.stringify(data),
                        callback: function () {
                            eventSet.toRollback(rowData);
                        }
                    };
                    var target = "tempo-mine-snapshot-manage-config-add-panel";
                    $m.loadHtml(url, $("body"), target, param);
                    return;
                }
                //直接恢复
                if (buttontype == '2') {
                    eventSet.toRollback(rowData);
                    return;
                }
                //取消
                if (buttontype == '3') {
                    $confirmDialog.dialog('close');
                    return;
                }
            });
        },

        /**
         * 回滚操作
         */
        toRollback: function (rowData) {
            var process = $("<div/>").tempoprogressbar();
            $.ajax({
                url: contextPath + '/api/ai/snapshot/findById',
                data: {
                    id: rowData.id
                },
                type: 'post',
                success: function (resultData) {
                    process.tempoprogressbar('destroy');
                    if (resultData.success) {
                        var analyseStatus = Eventbus.triggerHandler("getAnalyseStatus")[0];
                        var id = analyseStatus.getMainId();
                        var undoManager = analyseStatus.getUndoManager();
                        undoManager.clear();
                        var page = analyseStatus.getFlowPanel(id);
                        var board = page.panel.flowpanel('getBoard');
                        board.miningboard('destroy');
                        page.panel.flowpanel('clearFlowLog');
                        var resource = resultData.data;
                        var _flow = JSON.parse(resource.content);
                        // 如果有flow属性，则不用处理，否则构建流程
                        if (!_flow.flow && !_flow.logger) {
                            var content = {flow: _flow};
                            resource.content = JSON.stringify(content);
                        }
                        //版本管理恢复流程还使用之前的流程名称，不使用版本管理的名称
                        resource.name = $('span[linkid=' + id + ']').find('label').text();
                        Eventbus.trigger("renderBoard.mine", resource);
                        Eventbus.trigger("mining_board_change.mine");
                        Eventbus.trigger("saveAnalyseFromBar.mine", resultData.data.visitTime);
                        $confirmDialog.dialog('close');
                        $mainDialog.dialog('close');
                        process = $("<div/>").tempoprogressbar();
                        $.post(contextPath + '/api/ai/snapshot/rollback', {id: rowData.id}, function (result) {
                            process.tempoprogressbar('destroy');
                            $("<div/>").alert({
                                msg: TempoUtils.locale("mine.snapshot_rollback_success")
                            });
                        });
                    } else {
                        $("<div/>").alert({
                            msg: TempoUtils.locale("bi.snapshot_get_version_fail")
                        });
                    }
                },
                error: function () {
                    process.tempoprogressbar('destroy');
                }
            });
        }
    }

    init();
});